package io.bhex.app.kline;

import android.Manifest;
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.provider.MediaStore;
import android.support.design.widget.AppBarLayout;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import io.bhex.app.R;
import io.bhex.app.ScreenShot.BitmapUtils;
import io.bhex.app.ScreenShot.IScreenshotCallBack;
import io.bhex.app.ScreenShot.MediaContentCallback;
import io.bhex.app.ScreenShot.MediaContentObserver;
import io.bhex.app.ScreenShot.ShotScreenUtils;
import io.bhex.app.base.AppUI;
import io.bhex.app.kline.ui.BaseKlineActivity;
import io.bhex.app.qrcode.zxing.QRCodeEncoder;
import io.bhex.app.share.SHARE_MEDIA;
import io.bhex.app.share.ShareUtils;
import io.bhex.app.share.SystemShareUtils;
import io.bhex.app.utils.DialogUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.baselib.mvp.BasePresenter;
import io.bhex.baselib.mvp.BaseUI;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.ImageUtils;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.config.bean.ShareConfigBean;
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by BHEX.
 * User: gdy
 * Date: 2020/3/24
 * Time: 23:54
 */
public abstract   class BaseKlineShareActivity<P extends BasePresenter<V>, V extends AppUI & BaseUI>  extends BaseKlineActivity<P, V>
    implements  IScreenshotCallBack, EasyPermissions.PermissionCallbacks{


    protected static final float HEIGHT_ENTRUST_HEADER = 40f;//委托单头部高度
    protected static final float HEIGHT_LATEST_HEADER = 40f;//最新成交头部高度
    protected static final float VIEWPAGER_KLINE_HEIGHT_DEFAULT = 300f;//k线图viewpager竖屏默认高度  横屏高度为全屏高度-状态栏高度
    protected static final int WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 2;

    protected boolean forbidAppBarScroll;//是否禁止滑动appbar

    //默认是竖屏
    protected boolean isVerticalScreen = true;

    protected IScreenshotCallBack mScreenshotCallBack;
    protected Bitmap attachBitmap;
    protected View shareView;
    protected ImageView shareQrcodeImg;
    protected View sharePreView;
    protected ImageView sharePreViewImg;
    protected String resultPath;
    protected Bitmap resultBitmap;
    protected Handler mShotHandler;
    protected ShareConfigBean shareConfig;
    protected ImageView shareLogoImg;
    protected TextView shareName;
    protected TextView shareDesp;
    protected String shareUrl;


    protected HandlerThread mHandlerThread;
    protected MediaContentObserver mInternalObserver;
    protected MediaContentObserver mExternalObserver;
    protected ContentResolver mContentResolver;


    @Override
    public void screenshotTaken(final String path) {
        shotScreenShare();
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE) {
            //TODO 权限请求成功
            //ToastUtils.showLong("权限请求成功");
            shareDialogAction();
        } else {
            Toast.makeText(this, "request permission fail!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        DialogUtils.showDialogOneBtn(this, getString(R.string.string_reminder), getString(R.string.file_read_write_permission_hint), getString(R.string.string_i_know), false, new DialogUtils.OnButtonEventListener() {
            @Override
            public void onConfirm() {
                ToastUtils.showShort(getString(R.string.string_share_failed));
            }

            @Override
            public void onCancel() {
                ToastUtils.showShort(getString(R.string.string_share_failed));
            }
        });
    }

    /**
     * 自己：截屏分享
     */
    protected void shotScreenShare() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, getString(R.string.file_read_write_permission_hint), WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE, perms);
            return;
        }
        //弹出分享对话框
        Observable.create(emitter -> {
            shareDialogAction();
        }).subscribeOn(Schedulers.computation())
                .subscribe(o -> {

                });

    }

    /**
     * 分享对话框的弹出
     */
    protected void shareDialogAction(){
        Bitmap bitmap = ShotScreenUtils.shotScreen(BaseKlineShareActivity.this);
        if (bitmap != null) {
//                if (CommonUtil.isBhex(this)) {

            if (shareConfig != null && !TextUtils.isEmpty(shareConfig.getOpenUrl())) {
                //此处调整为 邀请地址不为空 用邀请地址，为空则用后端shareConfig配置地址
                Bitmap bitmapQR = QRCodeEncoder
                        .syncEncodeQRCode(TextUtils.isEmpty(shareUrl)?shareConfig.getOpenUrl():shareUrl,
                                PixelUtils.dp2px(50),
                                SkinColorUtil.getDefaultDark(this),
                                SkinColorUtil.getDefaultWhite(this),
                                BitmapUtils.getBitmapByres(BaseKlineShareActivity.this, R.mipmap.ic_launcher));

                BitmapUtils.saveBitmap(BaseKlineShareActivity.this,bitmapQR);

                attachBitmap = BitmapUtils.createBitmap3(shareView,
                        isVerticalScreen ?
                                PixelUtils.getScreenWidth() : (
                                PixelUtils.getScreenWidth() > PixelUtils.getScreenHeight() ?
                                        PixelUtils.getScreenWidth() : PixelUtils.getScreenHeight()),
                        PixelUtils.dp2px(80));

                BitmapUtils.saveBitmap(BaseKlineShareActivity.this,attachBitmap);

                resultBitmap = BitmapUtils.concatBitmap(BaseKlineShareActivity.this, isVerticalScreen, bitmap, attachBitmap);

                //      sharePreViewImg.setBackground(new BitmapDrawable(getResources(),resultBitmap));
                resultPath = BitmapUtils.saveBitmap(BaseKlineShareActivity.this,resultBitmap);
                runOnUiThread(()->{
                    shareQrcodeImg.setImageBitmap(bitmapQR);

                    showShare(resultPath, resultBitmap);

                });

            } else {
                resultPath = BitmapUtils.saveBitmap(BaseKlineShareActivity.this,bitmap);
                runOnUiThread(()->{
                    showShare(resultPath, bitmap);
                });
            }
        }
    }


    protected void showShare(final String resultPath, final Bitmap resultBitmap) {

        DialogUtils.showShareDialogOneBtn(this, "", resultPath, true,new DialogUtils.OnShareListener() {
            @Override
            public void onShareWx() {
                ShareUtils.share(SHARE_MEDIA.WEIXIN, resultBitmap);

            }

            @Override
            public void onShareWxCircle() {
                ShareUtils.share(SHARE_MEDIA.WEIXIN_CIRCLE, resultBitmap);
            }

            @Override
            public void onSavePic() {
                ImageUtils.saveImageToGallery(BaseKlineShareActivity.this, resultBitmap);
                ToastUtils.showShort(getString(R.string.string_save_success));
            }

            @Override
            public void onMore() {
                SystemShareUtils.shareImage(BaseKlineShareActivity.this,resultPath);
            }

            @Override
            public void onCancel() {

            }
        });

    }


    /**
     * 初始化监听
     *
     * @param contentResolver
     * @param screenshotCallBack
     */
    public void init(ContentResolver contentResolver, IScreenshotCallBack screenshotCallBack) {


        mContentResolver = contentResolver;
        mScreenshotCallBack = screenshotCallBack;
        mHandlerThread = new HandlerThread("Screenshot_Observer");
        mHandlerThread.start();
        mShotHandler = new Handler(mHandlerThread.getLooper());

        // 初始化
        mInternalObserver = new MediaContentObserver(MediaStore.Images.Media.INTERNAL_CONTENT_URI, mShotHandler, new MediaContentCallback() {
            @Override
            public void onChange(Uri contentUri, boolean selfChange) {
                handleMediaContentChange(contentUri);
            }
        });
        mExternalObserver = new MediaContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, mShotHandler, new MediaContentCallback() {
            @Override
            public void onChange(Uri contentUri, boolean selfChange) {
                handleMediaContentChange(contentUri);
            }
        });
    }

    // 添加监听
    public void register() {
        mContentResolver.registerContentObserver(
                MediaStore.Images.Media.INTERNAL_CONTENT_URI,
                false,
                mInternalObserver
        );
        mContentResolver.registerContentObserver(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                false,
                mExternalObserver
        );
    }

    // 注销监听 ondestroy()
    public void unregister() {
        mContentResolver.unregisterContentObserver(mInternalObserver);
        mContentResolver.unregisterContentObserver(mExternalObserver);
    }

    public static final String[] KEYWORDS = {
            "screenshot", "screen_shot", "screen-shot", "screen shot",
            "screencapture", "screen_capture", "screen-capture", "screen capture",
            "screencap", "screen_cap", "screen-cap", "screen cap"
    };

    /**
     * 读取媒体数据库时需要读取的列
     */
    public static final String[] MEDIA_PROJECTIONS = {
            MediaStore.Images.ImageColumns.DATA,
            MediaStore.Images.ImageColumns.DATE_TAKEN,
    };

    public void handleMediaContentChange(Uri contentUri) {
        Cursor cursor = null;
        try {
            // 数据改变时查询数据库中最后加入的一条数据
            cursor = this.getContentResolver().query(
                    contentUri,
                    MEDIA_PROJECTIONS,
                    null,
                    null,
                    MediaStore.Images.ImageColumns.DATE_ADDED + " desc limit 1"
            );

            if (cursor == null) {
                return;
            }
            if (!cursor.moveToFirst()) {
                return;
            }

            // 获取各列的索引
            int dataIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            int dateTakenIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATE_TAKEN);

            // 获取行数据
            String data = cursor.getString(dataIndex);
            long dateTaken = cursor.getLong(dateTakenIndex);

            // 处理获取到的第一行数据
            handleMediaRowData(data, dateTaken);

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
    }

    /**
     * 处理监听到的资源
     */
    public void handleMediaRowData(String data, long dateTaken) {
        long duration = 0;
        long step = 100;
        //设置最大等待时间为 500ms 手机保存会有延迟
        while (!checkScreenShot(data, dateTaken) && duration <= 500) {
            try {
                duration += step;
                Thread.sleep(step);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if (checkScreenShot(data, dateTaken)) {
            DebugLog.d("screenshot", data + " " + dateTaken);
            if (mScreenshotCallBack != null) {
                mScreenshotCallBack.screenshotTaken(data);
            }
        } else {
            DebugLog.d("screenshot", "Not screenshot event");
        }
    }

    /**
     * 判断是否是截屏
     */
    public boolean checkScreenShot(String data, long dateTaken) {
        if (data == null) {
            return false;
        }

        data = data.toLowerCase();
        // 判断图片路径是否含有指定的关键字之一, 如果有, 则认为当前截屏了
        for (String keyWork : KEYWORDS) {
            if (data.contains(keyWork)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 禁止AppbarLayout滑动
     *
     * @param forbid
     */
    protected void forbidAppBarScroll(boolean forbid) {
        if (forbid == forbidAppBarScroll) {
            return;
        }
    }

    /**
     * 设置AppBarLayout拖动回调
     *
     * @param dragCallback
     */
    private void setAppBarDragCallback(AppBarLayout.Behavior.DragCallback dragCallback) {
        /*LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) appBar.getLayoutParams();
        AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior();
        behavior.setDragCallback(dragCallback);*/
    }

    @Override
    public int getColorPrimary() {
        //return super.getColorPrimary();
        return ContextCompat.getColor(this,R.color.color_bg_2_night);
    }
}
